/**
 *  *2010-8-9 下午09:20:50  add 
 */
package com.base.myproject.client.HR.batchpro;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.base.myproject.client.HR.bcode.BcodeSelectDialog;
import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseGrid;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Administrator 2010-8-9 javazgw@gmail.com
 */
public class Contractitem extends ProcItem {
	boolean isinit = false;
	BcodeSelectDialog<TreeNodeModelData> bsd_add = null;
	
	//合同开始日期
	DateField contract_start_date;;
	//合同结束日期
	DateField contract_end_date;;
	//合同开始日期添加天数
	NumberField start_n; 
	//合同结束日期添加天数
	NumberField end_n; 
	Button save = new Button("保存");
	public Contractitem() {
		init();
	}

	public Contractitem(String name) {
		super(name);
	}

	private void init() {

	}

	@Override
	public Widget initwidget() {

		
		if(!isinit)
		{
		HorizontalPanel hpanel = new HorizontalPanel();
		createGrid();
		LayoutContainer lc = initProButtons();
		
		hpanel.add(grid);
		hpanel.add(lc);
		this.add(hpanel);
		isinit = true;
		Tools.setResize(grid, 0.8,0.95);
		Tools.setResize(lc, 0.2,0.95);
		}
		return this;
	}

	BaseStore<BusiObject> store = null;

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("contractstartdate");
		type.getField("contractstartdate").setType(Date.class);
		type.addField("contractsenddate");
		type.getField("contractsenddate").setType(Date.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("bcode_job");
		info.setKeyname(new String[] { "icode" });
	//	info.setSql("select contractstartdate,contractsenddate from bcode_job");
		info.setNeedAllRow("true");
		info.setForcenolimit("true");
		// info.setParent(mainstore);// 关联主表
		// info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		// info.setLinkparent_chile_columns(new String[] { "upicode" });//
		// 关联主表字段
		store = new BaseStore<BusiObject>(type, info,false);
		return store;
	}

	BaseGrid grid = null;

	BaseGrid createGrid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C3 = new ColumnConfig("icode",
				"icode", 180);
		columns.add(C3);
		
		ColumnConfig C1 = new ColumnConfig("contractstartdate",
				"合同开始日期", 180);
		C1.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C1);
		ColumnConfig C2 = new ColumnConfig("contractsenddate",
				"合同终止日期", 180);
		C2.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C2);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid(getStore(), cm);
		cbs.setSelectionMode(SelectionMode.SIMPLE);
		grid.setSelectionModel(cbs);
		return grid;
	}
	
	LayoutContainer initProButtons()
	{
		LayoutContainer lc = new LayoutContainer();
		TableLayout tl = new TableLayout(2);
		lc.setLayout(tl);
		
		TableData td1 = new TableData();
		td1.setColspan(1);
		TableData td2 = new TableData();
		td2.setColspan(2);
		
		 bsd_add = new BcodeSelectDialog<TreeNodeModelData>(){
			public void doposted(List<TreeNodeModelData> modeldatalist) {
				if(modeldatalist.size()>0)
				{
					this.setEmptyText("已经选择了数据");
					
					List<TreeNodeModelData>  selectchecklist=bsd_add.getTree().getCheckedSelection();
					
					if(selectchecklist.size()<=0)
					{
						MessageBox.alert("错误", "请选择“发放花红人员”", null	);
						return;
					}
					String bcodestr = "";
					for(TreeNodeModelData tnmd:selectchecklist)
					{
						BusiObject bo = new BusiObject();
						
						bcodestr +=" systembcode like '"+tnmd.get("systembcode")+"%25' or ";

					}
					bcodestr +=" 1=2";
					GWT.log("bcodestr ="+bcodestr);
					
					
					String sql  = "select icode, contractstartdate,contractsenddate from bcode_job where exists (select * from systembcode_view where systembcode_view.bcode = bcode_job.bcode  and ( "+bcodestr+"))";
					GWT.log("sql ="+sql);
					store.getStoreinfo().setSql(sql);
					store.reload();
				}
			}

		};
		bsd_add.setNeesreselect(false);
		bsd_add.setEmptyText("未选择数据");
		bsd_add.setExpanded();
		bsd_add.setCheckNodes(CheckNodes.BOTH);
		bsd_add.addListener(Events.Changed, getListener());
		
		 contract_start_date = new DateField();
		contract_start_date.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		
		 contract_end_date = new DateField();
		contract_end_date.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		 start_n = new NumberField();
		 end_n = new NumberField();
		
		
		
		save.addListener(Events.OnClick,  getListener());
		lc.add(new LabelField("选择人员："),td1);
		lc.add(bsd_add,td1);
		
		lc.add(new LabelField("调整合同开始日期为："),td1);
		lc.add(contract_start_date,td1);
		
		lc.add(new LabelField("合同开始日期加（天）："),td1);
		lc.add(start_n,td1);
		
		
		lc.add(new LabelField("调整合同终止日期为："),td1);
		lc.add(contract_end_date,td1);
		
		lc.add(new LabelField("合同终止日期加（天）："),td1);
		lc.add(end_n,td1);
		
		lc.add(save,td2);
		
		contract_start_date.addListener(Events.Changed, getListener());
		start_n.addListener(Events.Changed, getListener());
		contract_end_date.addListener(Events.Changed, getListener());
		end_n.addListener(Events.Changed, getListener());
		return lc;
	}
	
	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                                                                            
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                      
				try {                                                        
					if (sync == 1) {                                           
						if (be.getType() == Events.OnClick) {                     
							if (be.getSource().equals(save)) {     
								store.trySave();
							}                                                      
						} else if (be.getType() == Events.Changed) {              
							if (be.getSource().equals(bsd_add)) {

								List<TreeNodeModelData>  selectchecklist=bsd_add.getTree().getCheckedSelection();
								
								if(selectchecklist.size()<=0)
								{
									MessageBox.alert("错误", "请选择“发放花红人员”", null	);
									return;
								}
								String bcodestr = "";
								for(TreeNodeModelData tnmd:selectchecklist)
								{
									BusiObject bo = new BusiObject();
									
									bcodestr +=" systembcode like '"+tnmd.get("systembcode")+"%' or ";

								}
								bcodestr +=" 1=2";
								GWT.log("bcodestr ="+bcodestr);
								
								
								String sql  = "select icode, contractstartdate,contractsenddate from bcode_job where exists (select * from systembcode_view where systembcode_view.bcode = bcode_job.bcode  and ( "+bcodestr+"))";
								GWT.log("sql ="+sql);
								
								store.getStoreinfo().setSql(sql);
								store.reload();
							}     
							
							else if (be.getSource().equals(contract_start_date)) {
								int i = 0;
								if(contract_start_date!=null)
								for(BusiObject bo:getStore().getModels())
								{
									
//									bo.set("contractstartdate", contract_start_date.getValue());
									grid.setValue(i,"contractstartdate", contract_start_date.getValue());
									i++;
								}
//								grid.getView().refreshRow(row)
							}
							else if (be.getSource().equals(start_n)) {
								if(start_n!=null)
								{
								int i = 0;
								for(BusiObject bo:getStore().getModels())
								{
									
									GWT.log(""+((Date)bo.get("contractstartdate")).getTime()+60*60*24*start_n.getValue().intValue());
									GWT.log(((Date)bo.get("contractstartdate")).getDay()+"");
									if(bo.get("contractstartdate")!=null)
										grid.setValue(i,"contractstartdate", new Date(((Date)bo.get("contractstartdate")).getTime()+1000*60*60*24*start_n.getValue().intValue()));
									i++;
								}
								}
							}

							else if (be.getSource().equals(contract_end_date)) {
								int i = 0;
								if(contract_end_date!=null)
								for(BusiObject bo:getStore().getModels())
								{
//									bo.set("contractenddate", contract_end_date.getValue());
									grid.setValue(i,"contractsenddate", contract_end_date.getValue());
									i++;
								}
							} else if (be.getSource().equals(end_n)) {
								if(end_n!=null)
								{
									int  i = 0 ;
								for(BusiObject bo:getStore().getModels())
								{
									GWT.log(((Date)bo.get("contractsenddate")).getDay()+"");
//									bo.set("contractstartdate", contract_start_date.getValue());
									if(bo.get("contractsenddate")!=null)
										grid.setValue(i,"contractsenddate", new Date(((Date)bo.get("contractsenddate")).getTime()+1000*60*60*24*end_n.getValue().intValue()));
									i++;
								}
								}
							}
						} else if (be.getType() == Events.KeyUp) {               
							if (be instanceof ComponentEvent) {                    
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{                                                    
								}                                                    
							}                                                      
						}                                                        
					}                                                          
				} finally {                                                  
					sync--;                                                    
				}                                                            
			}                                                              
                                                                     
		};                                                               
		return defaultlistener;                                          
	}      
}
